package com.bryant.bryant_weather.ui.login

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bryant.bryant_weather.MainActivity

import com.bryant.bryant_weather.base.BaseBindingActivity
import com.bryant.bryant_weather.bean.LoginRequest
import com.bryant.bryant_weather.databinding.AcLoginBinding
import com.bryant.bryant_weather.storage.TokenPreferences
import com.bryant.bryant_weather.utils.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : BaseBindingActivity<AcLoginBinding>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 绑定登录按钮控件， 并设置点击事件
        binding.tvLogin.setOnClickListener{
           toLogin ()
        }
    }

    override fun initBinding(layoutInflater: LayoutInflater): AcLoginBinding {
        return AcLoginBinding.inflate(layoutInflater)
    }

    @SuppressLint("ShowToast")
    fun toLogin () {
       // 1. 获取用户输入的账号密码
        val username = binding.etUsername.text.toString()
        val password = binding.etPassword.text.toString()

        // 2. 判断账户密码是否为空
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show()
             return
        }

        // 3. 登录逻辑
        try {
            // 创建协程作用域
            lifecycleScope.launch (Dispatchers.Main){
                // 1. 创建登录请求对象， 传入用户输入的账号密码
                val request = LoginRequest(username, password)

                // 2. 在IO线程中发送请求登录
                val res = withContext(Dispatchers.IO){
                    RetrofitClient.apiService.login(request)
                }

                // 3. 发送完成 - 检查响应码
                if(res.code == 10000){
                    // 1. 登录成功 - 获取token
                    val token = res.data?.token
                    // 2. 持久化token
                    // 先处理token为空情况
                    if (token.isNullOrEmpty()) {
                        Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                        return@launch
                    }
                    TokenPreferences.getInstance(this@LoginActivity).saveToken(token.toString())
                    // 3. 登录成功提示
                    Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_SHORT).show()
                    // 4. 跳转到主页
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                }else{
                    Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                }
            }

        }catch (e: Exception){
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
        }
    }
}